package com.example.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/api/finance")
@Tag(name = "财务管理", description = "财务数据的管理和统计")
public class FinanceController {

    @GetMapping("/overview")
    @Operation(summary = "获取财务概览")
    public ResponseEntity<Map<String, Object>> getFinanceOverview(
            @RequestParam(required = false) String period) {
        
        Map<String, Object> overview = new HashMap<>();
        
        // 今日数据
        Map<String, Object> today = new HashMap<>();
        today.put("income", new BigDecimal("2580.50"));
        today.put("expense", new BigDecimal("450.00"));
        today.put("profit", new BigDecimal("2130.50"));
        today.put("orders", 28);
        
        // 本月数据
        Map<String, Object> thisMonth = new HashMap<>();
        thisMonth.put("income", new BigDecimal("78500.00"));
        thisMonth.put("expense", new BigDecimal("12300.00"));
        thisMonth.put("profit", new BigDecimal("66200.00"));
        thisMonth.put("orders", 856);
        
        // 本年数据
        Map<String, Object> thisYear = new HashMap<>();
        thisYear.put("income", new BigDecimal("945000.00"));
        thisYear.put("expense", new BigDecimal("145000.00"));
        thisYear.put("profit", new BigDecimal("800000.00"));
        thisYear.put("orders", 10250);
        
        overview.put("today", today);
        overview.put("thisMonth", thisMonth);
        overview.put("thisYear", thisYear);
        
        // 趋势数据
        List<Map<String, Object>> trends = new ArrayList<>();
        for (int i = 6; i >= 0; i--) {
            Map<String, Object> trend = new HashMap<>();
            trend.put("date", LocalDateTime.now().minusDays(i).toLocalDate());
            trend.put("income", new BigDecimal(2000 + (int)(Math.random() * 1000)));
            trend.put("expense", new BigDecimal(300 + (int)(Math.random() * 200)));
            trends.add(trend);
        }
        overview.put("trends", trends);
        
        return ResponseEntity.ok(overview);
    }

    @GetMapping("/income")
    @Operation(summary = "获取收入列表")
    public ResponseEntity<Map<String, Object>> getIncomeList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        List<Map<String, Object>> incomeList = Arrays.asList(
            createIncomeData(1L, "订单收入", new BigDecimal("156.00"), "WO20241209001", "洗护服务费"),
            createIncomeData(2L, "订单收入", new BigDecimal("89.50"), "WO20241209002", "干洗服务费"),
            createIncomeData(3L, "订单收入", new BigDecimal("234.00"), "WO20241209003", "熨烫服务费"),
            createIncomeData(4L, "会员充值", new BigDecimal("500.00"), "MB20241209001", "会员卡充值"),
            createIncomeData(5L, "订单收入", new BigDecimal("78.00"), "WO20241209004", "洗护服务费")
        );
        
        Map<String, Object> response = createPagedResponse(incomeList, page, size);
        return ResponseEntity.ok(response);
    }

    @GetMapping("/expense")
    @Operation(summary = "获取支出列表")
    public ResponseEntity<Map<String, Object>> getExpenseList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        List<Map<String, Object>> expenseList = Arrays.asList(
            createExpenseData(1L, "设备维护", new BigDecimal("200.00"), "洗衣机维护费用"),
            createExpenseData(2L, "水电费", new BigDecimal("150.00"), "本月水电费"),
            createExpenseData(3L, "洗涤剂采购", new BigDecimal("300.00"), "洗涤用品采购"),
            createExpenseData(4L, "员工工资", new BigDecimal("5000.00"), "本月员工工资"),
            createExpenseData(5L, "房租", new BigDecimal("3000.00"), "店面租金")
        );
        
        Map<String, Object> response = createPagedResponse(expenseList, page, size);
        return ResponseEntity.ok(response);
    }

    @PostMapping("/income")
    @Operation(summary = "添加收入记录")
    public ResponseEntity<Map<String, Object>> createIncome(@RequestBody Map<String, Object> income) {
        Map<String, Object> newIncome = createIncomeData(
            System.currentTimeMillis(),
            (String) income.get("type"),
            new BigDecimal(income.get("amount").toString()),
            (String) income.get("orderNo"),
            (String) income.get("description")
        );
        return ResponseEntity.ok(newIncome);
    }

    @PostMapping("/expense")
    @Operation(summary = "添加支出记录")
    public ResponseEntity<Map<String, Object>> createExpense(@RequestBody Map<String, Object> expense) {
        Map<String, Object> newExpense = createExpenseData(
            System.currentTimeMillis(),
            (String) expense.get("type"),
            new BigDecimal(expense.get("amount").toString()),
            (String) expense.get("description")
        );
        return ResponseEntity.ok(newExpense);
    }

    @PutMapping("/income/{id}")
    @Operation(summary = "更新收入记录")
    public ResponseEntity<Map<String, Object>> updateIncome(
            @PathVariable Long id,
            @RequestBody Map<String, Object> income) {
        Map<String, Object> updatedIncome = createIncomeData(
            id,
            (String) income.get("type"),
            new BigDecimal(income.get("amount").toString()),
            (String) income.get("orderNo"),
            (String) income.get("description")
        );
        return ResponseEntity.ok(updatedIncome);
    }

    @PutMapping("/expense/{id}")
    @Operation(summary = "更新支出记录")
    public ResponseEntity<Map<String, Object>> updateExpense(
            @PathVariable Long id,
            @RequestBody Map<String, Object> expense) {
        Map<String, Object> updatedExpense = createExpenseData(
            id,
            (String) expense.get("type"),
            new BigDecimal(expense.get("amount").toString()),
            (String) expense.get("description")
        );
        return ResponseEntity.ok(updatedExpense);
    }

    @DeleteMapping("/income/{id}")
    @Operation(summary = "删除收入记录")
    public ResponseEntity<Void> deleteIncome(@PathVariable Long id) {
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/expense/{id}")
    @Operation(summary = "删除支出记录")
    public ResponseEntity<Void> deleteExpense(@PathVariable Long id) {
        return ResponseEntity.ok().build();
    }

    @GetMapping("/report")
    @Operation(summary = "获取财务报表")
    public ResponseEntity<Map<String, Object>> getFinanceReport(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String type) {
        
        Map<String, Object> report = new HashMap<>();
        report.put("totalIncome", new BigDecimal("78500.00"));
        report.put("totalExpense", new BigDecimal("12300.00"));
        report.put("netProfit", new BigDecimal("66200.00"));
        report.put("profitMargin", 84.3);
        
        // 分类统计
        Map<String, Object> incomeByType = new HashMap<>();
        incomeByType.put("订单收入", new BigDecimal("70000.00"));
        incomeByType.put("会员充值", new BigDecimal("8500.00"));
        
        Map<String, Object> expenseByType = new HashMap<>();
        expenseByType.put("员工工资", new BigDecimal("5000.00"));
        expenseByType.put("房租", new BigDecimal("3000.00"));
        expenseByType.put("水电费", new BigDecimal("1500.00"));
        expenseByType.put("设备维护", new BigDecimal("2000.00"));
        expenseByType.put("其他", new BigDecimal("800.00"));
        
        report.put("incomeByType", incomeByType);
        report.put("expenseByType", expenseByType);
        
        return ResponseEntity.ok(report);
    }

    // 辅助方法
    private Map<String, Object> createIncomeData(Long id, String type, BigDecimal amount, 
                                                String orderNo, String description) {
        Map<String, Object> income = new HashMap<>();
        income.put("id", id);
        income.put("type", type);
        income.put("amount", amount);
        income.put("orderNo", orderNo);
        income.put("description", description);
        income.put("createTime", LocalDateTime.now());
        income.put("status", "confirmed");
        return income;
    }

    private Map<String, Object> createExpenseData(Long id, String type, BigDecimal amount, String description) {
        Map<String, Object> expense = new HashMap<>();
        expense.put("id", id);
        expense.put("type", type);
        expense.put("amount", amount);
        expense.put("description", description);
        expense.put("createTime", LocalDateTime.now());
        expense.put("status", "confirmed");
        return expense;
    }

    private Map<String, Object> createPagedResponse(List<Map<String, Object>> data, int page, int size) {
        int start = page * size;
        int end = Math.min(start + size, data.size());
        List<Map<String, Object>> pagedData = start < data.size() ? data.subList(start, end) : new ArrayList<>();

        Map<String, Object> response = new HashMap<>();
        response.put("content", pagedData);
        response.put("totalElements", data.size());
        response.put("totalPages", (int) Math.ceil((double) data.size() / size));
        response.put("size", size);
        response.put("number", page);
        return response;
    }
}
